//
//  YZFetterViewController.swift
//  YZFetter
//
//  Created by 康凯 on 2017/7/12.
//  Copyright © 2017年 康凯. All rights reserved.
//

import UIKit
import RxSwift
import CoreBluetooth

let imageScaleRate: CGFloat = 1.625     // 图片的宽高比
let themeColor: UIColor = UIColor.init(rgbHex: "1fc69e")

class YZFetterViewController: UIViewController {

    let bag = DisposeBag()
    
    let blueToothManager: YZBlueToothManager = YZBlueToothManager.shareInstances
    var peripheralDataSource: [CBPeripheral] = []
    var topView: UIView!
    var isPushed: Bool!
//    var peripheralMacAddress: Data!
    
    var emptyLabel: UILabel = {
        let tempLabel = UILabel()
        tempLabel.textAlignment = .center
        tempLabel.text = "暂无蓝牙设备，确认激活后点击刷新按钮"
        tempLabel.font = k_labelFont
        tempLabel.numberOfLines = 0
        tempLabel.textColor = UIColor.lightGray
        tempLabel.backgroundColor = UIColor.clear
        return tempLabel
    }()
    
    var tableView: UITableView = {
        let tempTableView = UITableView()
        tempTableView.backgroundColor = UIColor.white
        tempTableView.tableFooterView = UIView()
        return tempTableView
    }()
    
    init() {
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        initNavItem()
        initSubViews()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        isPushed = false
        reloadDate()
    }
    
    func initNavItem() {
        title = "蓝牙列表"
        view.backgroundColor = UIColor.white
    }
    
    func initSubViews() {
        
        topView = UIView()
        topView.backgroundColor = themeColor
        view.addSubview(topView)
        topView.snp.makeConstraints { (make) in
            make.top.equalTo(view).offset(64)
            make.left.right.equalTo(view)
            make.height.equalTo(is_iPhone_5_orLess ? 200 : 230)
        }
        
        let imageView = UIImageView()
        imageView.image = #imageLiteral(resourceName: "lanya")
        topView.addSubview(imageView)
        imageView.snp.makeConstraints { (make) in
            make.centerX.equalTo(topView)
            make.centerY.equalTo(topView).offset(-20)
            make.size.equalTo(CGSize.init(width: kScreen_Width - 60, height: (kScreen_Width - 60) / imageScaleRate))
        }
        
        let hintMsg = UILabel()
        hintMsg.text = "请旋转激活旋钮激活设备"
        hintMsg.textColor = UIColor.white
        hintMsg.backgroundColor = UIColor.clear
        hintMsg.textAlignment = .center
        hintMsg.font = UIFont.systemFont(ofSize: 17)
        topView.addSubview(hintMsg)
        hintMsg.snp.makeConstraints { (make) in
            make.top.equalTo(imageView.snp.bottom).offset(-10)
            make.left.right.equalTo(view)
            make.height.equalTo(30)
        }
        
        tableView.delegate = self
        tableView.dataSource = self
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(topView.snp.bottom)
            make.right.left.equalTo(view)
            make.bottom.equalTo(view).offset(-60)
        }
        
        view.addSubview(emptyLabel)
        emptyLabel.snp.makeConstraints { (make) in
            make.center.equalTo(tableView)
            make.size.equalTo(CGSize.init(width: kScreen_Width - 100, height: 100))
        }
        
        let refreshBtn = UIButton()
        refreshBtn.setTitle("刷    新", for: .normal)
        refreshBtn.setTitleColor(UIColor.white, for: .normal)
        refreshBtn.titleLabel?.font = k_labelFont
        refreshBtn.backgroundColor = themeColor
        refreshBtn.layer.cornerRadius = 20
        refreshBtn.addTarget(self, action: #selector(YZFetterViewController.reloadDate), for: .touchUpInside)
        view.addSubview(refreshBtn)
        refreshBtn.snp.makeConstraints { (make) in
            make.top.equalTo(tableView.snp.bottom).offset(10)
            make.left.equalTo(view).offset(20)
            make.right.equalTo(view).offset(-20)
            make.bottom.equalTo(view).offset(-10)
        }
        
        
        blueToothManager.peripheralList.asObservable().subscribe(onNext: {
            [weak self] peripherals in
            self?.peripheralDataSource = peripherals
            self?.emptyLabel.isHidden = true
            self?.tableView.reloadSections(IndexSet.init(integer: 0), with: .automatic)
        }).addDisposableTo(bag)
        
        _ = blueToothManager.characteristicList.asObserver().subscribe (onNext: { [weak self] characteristics in
            guard characteristics.count != 0 else {
                return
            }

//            if characteristics[0].service.uuid.uuidString == systemInfoUUID {
//                self?.peripheralMacAddress = characteristics[0].value
//            }
            
            if characteristics[0].service.uuid == CBUUID.init(string: customerServiceUUID) {
                if !(self?.isPushed)! {
                    let detVC = YZFetterDetailController()
                    self?.isPushed = true
                    detVC.characteristics = characteristics
                    detVC.peripheralName = self?.blueToothManager.peripheral?.name
                    self?.navigationController?.pushViewController(detVC, animated: true)
                }
            }

        }).addDisposableTo(bag)
    }
    
    // MARK:- CustomFunc
    // 刷新列表
    func reloadDate() {
        blueToothManager.refreshBT()
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { 
            if self.peripheralDataSource.count == 0 {
                self.emptyLabel.isHidden = false
            }
        }
    }
}

extension YZFetterViewController: UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1;
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return peripheralDataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
        if cell == nil {
            cell = UITableViewCell.init(style: .default, reuseIdentifier: "Cell")
        }
        cell?.selectionStyle = .none
        cell?.imageView?.image = #imageLiteral(resourceName: "icon_bluetooth")
        cell?.textLabel?.text = peripheralDataSource[indexPath.row].name
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
}

extension YZFetterViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//        let selectedPeripheral = peripheralDataSource[indexPath.row]
        blueToothManager.connect(to: peripheralDataSource[indexPath.row])
    }
}









